package com.chinastock.log;

import com.chinastock.Constant;
import com.chinastock.model.AppMessage;
import org.apache.logging.log4j.ThreadContext;
import org.reactivestreams.Publisher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * @author zhangfan.it
 * @date 2021/2/3
 */
public class ExtractBodyServerHttpResponseDecorator extends ServerHttpResponseDecorator {
    private static final Logger log = LoggerFactory.getLogger(LogName.BIZ);
    private static final String LOG_TYPE = "response";

    private final ServerWebExchange exchange;
    private final String excludes;
    private final boolean isOn;

    public ExtractBodyServerHttpResponseDecorator(ServerWebExchange exchange, String excludes, boolean isOn) {
        super(exchange.getResponse());
        this.exchange = exchange;
        this.excludes = excludes;
        this.isOn = isOn;
    }

    @Override
    public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
        if (!isOn) {
            return super.writeWith(body);
        }

        return super.writeWith(Flux.from(body).map(dataBuffer -> {
            recordResponse(dataBuffer);
            return dataBuffer;
        }));
    }

    @Override
    public Mono<Void> writeAndFlushWith(Publisher<? extends Publisher<? extends DataBuffer>> body) {
        if (!isOn) {
            return super.writeAndFlushWith(body);
        }

        return super.writeAndFlushWith(Flux.from(body).map(x -> Flux.from(x).map(dataBuffer -> {
            recordResponse(dataBuffer);
            return dataBuffer;
        })));
    }

    private void recordResponse(DataBuffer dataBuffer) {
        AppMessage appMessage = new AppMessage();
        appMessage.setUrl(exchange.getRequest().getURI().getPath());
        MediaType type = exchange.getRequest().getHeaders().getContentType();
        String typeStr = type == null ? "UnknownType" : type.getSubtype();
        appMessage.setContentType(typeStr);
        appMessage.setType(LOG_TYPE);
        appMessage.setHeaders(exchange.getRequest().getHeaders().toSingleValueMap());
        appMessage.setObj(StandardCharsets.UTF_8.decode(dataBuffer.asByteBuffer()).toString());
        appMessage.setExcludes(excludes);
        log.info(appMessage.toString());
    }
}
